<?php
class indexApp {



    /**
     * 登录
     * 获取用户session_key
     * @param $params
     */
    public function index(){
        ob_end_clean();
        $cid = Session::$user['customerId'];
        $openid =  Session::$user['appopenid'];
        $data = ['openid'=>$openid,'customerId'=>$cid,'session'=>Session::$user];
        Output::instance()->object($data);
    }

    /**
     * 用户上传图片
     * @param $params
     */
    public function getUploadImage($params){
        $fileinfo = $_FILES["file"];
        $fileName = $fileinfo['tmp_name'];

        $fname=$fileName.time().".png";
		
        if(file_exists($fileName)){
            $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
            if(!$out->code){
                $imgurl = $out->path;
                $data['url']=$imgurl;
				Log::write("图片上传结果  ".$data['url']);
                Output::instance()->object($data);
            }else{
                Output::instance()->object($out->code);
            }
        }
    }
    /**
     * 首页用户商品列表
     * @param $openid
     */
    public function getProductList($start=0,$limit=10,$order='updateTime', $order = 'updateTime', $orderBy = 'desc'){
        $cid = Session::$user['customerId'];
        Session::$user['userName'];
        Session::switchCustomer(0);
        $ModuleProduct = M('module_product');
        $Mivendor = M('mivendor');
        Session::switchCustomer($cid);
        $User = M('user');
        $userId = Session::$user['userId'];
        $default = $Mivendor->alias('v')
            ->field('v.id as vId,v.fromCustomerUserId,v.status,v.createTime as VcreateTime,v.certificaTime,c.id as cId,c.*')
            ->join('LEFT JOIN wx_vendor_config as c on v.cId=c.cid')
            ->where(['v.userId'=>$userId,'v.cId'=>$cid,'deleted'=>0])
            ->find();
        $limitedProductNum = $default['limitedProductNum'];
        if($default['status']==3){
            $limitedProductNum = $default['auditedProductNum'];
        }
        $userlist = $ModuleProduct->field('id,name,picUrl,inventoryCount,fixedPrice,isRemoved')
            ->where(['vId'=>$default['vId'],'deleted'=>0])
            ->limit($start,$limit)
            ->order("$order $orderBy")
            ->select();
        $userlistCount = $ModuleProduct->field('id,name,picUrl,inventoryCount,fixedPrice,isRemoved')
            ->where(['vId'=>$default['vId'],'deleted'=>0])
            ->count();
        $canAddProductNum = $limitedProductNum-$userlistCount;

        $data = [
            'results'=>$userlist,
            'vId'=>$default['vId'],
            'countnum'=>$canAddProductNum
        ];
        Output::instance()->objArray($data,$userlistCount);

    }

    /**
     * 商品编辑
     * @param $id
     */
    public function editProduct($id)
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $ModuleProduct = M('module_product');
        $Mivendor = M('mivendor');
        Session::switchCustomer($cid);
        $userId = Session::$user['userId'];
        $default = $Mivendor->alias('v')
            ->field('v.id as vId,v.fromCustomerUserId,v.status,v.createTime as VcreateTime,v.certificaTime,c.id as cId,c.*')
            ->join('LEFT JOIN wx_vendor_config as c on v.cId=c.cid')
            ->where(['v.userId'=>$userId,'v.cId'=>$cid])
            ->find();
        $limitedProductNum = $default['limitedProductNum'];
        if($default['status']==3){
            $limitedProductNum = $default['auditedProductNum'];
        }

        $productCount = $ModuleProduct->field('id,name,picUrl,inventoryCount,fixedPrice,isRemoved')
            ->where(['vId'=>$default['vId'],'deleted'=>0])
            ->select();

        $canAddProductNum = $limitedProductNum-count($productCount);

        $result = $ModuleProduct->field('id,name,fixedPrice,inventoryCount,picUrl,picUrl1,description,isRemoved')
            ->where(['id'=>$id])->find();

        $data = ['result' => $result,'countnum'=>$canAddProductNum,'vId'=>$default['vId']];

        Output::instance()->object($data);
    }

    /**
     *添加商品/编辑商品
     * @param $id
     */
    public function addProduct($id,$name,$vId,$description,$inventoryCount,$inventory,$inventoryCount,$isRemoved,$fixedPrice,$picUrl,$picUrl1)
    {

       $a =  R('Product/saveProduct', array($id,$name,NUll,$vId,$description,NULL,NULL,NULL,NULL,NULL,0,$inventory,$inventoryCount,Null,NULL,NULL,null,$isRemoved,$picUrl,$picUrl1,NULl,NULL,$fixedPrice,
           NULL,NULL,null,NULL,NULL, 0));

    }

    /**
     * 删除商品
     * @param $id
     */
    public function deleteProduct($id)
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $ModuleProduct = M('module_product');
        Session::switchCustomer($cid);
        $where['deleted']=1;
        $where['updateTime'] = date('Y-m-d H:m:s',time());
        $update = $ModuleProduct->where(['id'=>$id])->save($where);
        Output::instance()->object($update);
    }
    //获得当前用户身份
    public static function getIdentity(){
        $cid = Session::$user['customerId'];
        $userId=  Session::$user["userId"];
        Session::switchCustomer(0);
        $agentModel = M('vendor_agent');
        $vendorModel = M('mivendor');
        Session::switchCustomer($cid);
        $id = $agentModel->where("userId=$userId and deleted=0")->getField("id");
        if($id){
            $result["identity"]="agent";
            $result["id"]=$id;
            Output::instance()->object($result);
            return;
        }
        $id = $vendorModel->where("userId=$userId and deleted=0")->getField("id");
        if($id){
            $result["identity"]="vendor";
            $result["id"]=$id;
            Output::instance()->object($result);
            return;
        }
        $result["identity"]="nomal";
		$visitResult = self::userVisit(0,10,1);
		$result["count"]=$visitResult['count'];
		if($visitResult['count']==1){
			 $result["vid"] = $visitResult['arr'][0]['vid'];
		}
        Output::instance()->object($result);
        return;
    }
    //激活渠道商
    public static function activeAgent($id){
        $cid = Session::$user["customerId"];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        Session::switchCustomer($cid);
		$oldUserId = $agentModel->where("id=$id")->getField("userId");
		if($oldUserId){
			Output::instance()->resultCode(code_sql_error);
			return;
		}
        $data['userId']=$userId;
        $data['activationTime'] = date("Y-m-d H:i:s");
        $result = $agentModel->where("id=$id")->save($data);
        if($result===false){
            Output::instance()->resultCode(code_sql_error);
        }else{
            Output::instance()->resultCode();
        }
    }
    //渠道商首页
    public static function channelVendor($id,$start,$limit){
        $cid = Session::$user["customerId"];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $start = $start*$limit;
        $arr = $vendorModel->alias("a")
            ->join("inner join wx_store b on a.id=b.vId")
            ->where("a.vendorAgent=$id and a.deleted=0 and a.cId=$cid and b.deleted=0")
            ->limit($start,$limit)
            ->group("a.id")
            ->order("b.updateTime desc")
            ->field("b.id,b.vId,b.picUrl,b.name")
            ->select();
        if($arr){
            $count = $vendorModel->alias("a")
                ->join("inner join wx_store b on a.id=b.vId")
                ->where("a.vendorAgent=$id and a.deleted=0 and a.cId=$cid and b.deleted=0")
                ->group("a.id")
                ->order("b.updateTime desc")
                ->field("b.id")
                ->select();
            $count = count($count);
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    //普通用户首页
    public static function userVisit($start=0,$limit=10,$self=0){
        $cid = Session::$user["customerId"];
        $userId = Session::$user['userId'];
        Session::switchCustomer($cid);
        $vendorVisit = M("vendor_visit_log");
        $start = $start*$limit;
        $where['a.userId']=array("eq",$userId);
        $where["b.deleted"]=array("eq",0);
        $arr = $vendorVisit->alias("a")
            ->join("inner join wx_store b on a.storeId=b.id")
            ->where($where)
            ->limit("$start,$limit")
            ->field("b.id,a.vid,b.picUrl,b.name")
            ->order("a.createTime desc")
			->group("a.vid")
            ->select();
        if($arr){
            $count = $vendorVisit->alias("a")
                ->join("inner join wx_store b on a.storeId=b.id")
                ->where($where)
				->field("b.id")
				->group("a.vid")
                ->count();
				$count = count($count);
            
        }else{
			$arr = $vendorVisit->table("wx_store")
            ->where("vid=1188 and deleted=0")
            ->field("id,vId as vid,picUrl,name")
            ->select();
			 $count = 1;
            //Output::instance()->resultCode();
        }
		if($self==1){
			$result['count']=$count;
			$result['arr']=$arr;
			return $result;
		}else{
			Output::instance()->objArray($arr,$count);
		}
    }
    //渠道二维码
    public static function channelQrcode($id){
        $cid = Session::$user["customerId"];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        Session::switchCustomer($cid);
        $vendorOpenCode = $agentModel->where("id=$id")->getField("vendorOpenCode");
        if(!$vendorOpenCode){
            $path = WeixinApi::createwxaqrcode("page/vendorActivate/vendorActivate?id=$id",date("YmdHis").$id.".jpg");
            $vendorOpenCode = $path->path;
            $agentModel->where("id=$id")->setField("vendorOpenCode",$vendorOpenCode);
        }
        $result['code']=$vendorOpenCode;
        Output::instance()->object($result);
    }
    //渠道商家统计
    public static function getVendorStatistics($id,$search=null,$start=0,$limit=10,$order=null){
        $cid = Session::$user["customerId"];
        $start*=$limit;
        !$order?$order="b.name asc":"";
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        $where['a.cid']=array("eq",$cid);
        $where['a.vendorAgent']=array("eq",$id);
        $where["b.deleted"]=array("eq",0);
        $nowtime = date("Y-m-1 0:0:0");
        $prevTime=date('Y-m-1 0:0:0',strtotime("$nowtime -1 month"));
        if($search){
            $condition['_logic'] = 'OR';
			$condition["b.name"]=array("like",'%'.$search.'%');
			$condition["b.address"]=array("like","%".$search."%");
			$where["_complex"]=$condition;
        }
        Session::switchCustomer($cid);
        $arr = $vendorModel->alias("a")
            ->join("inner join wx_store b on a.id=b.vId")
            ->where($where)
            ->field("b.id,b.name,b.picUrl,a.balance,b.vId")
            ->limit($start,$limit)
            ->order($order)
            ->group("a.id")
            ->select();
        if($arr){
			foreach($arr as $key=>$value){
				$arr[$key]['balance'] = number_format($value['balance'],2);
			}
            $count =  $vendorModel->alias("a")
                ->join("inner join wx_store b on a.id=b.vId")
                ->where($where)
                ->field("b.id")
                ->select();
            $count = count($count);
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    //获得商家配置
    public static function getVendorConfig(){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        Session::switchCustomer($cid);
        $configInfo = $vendorConfig->where("cid=$cid")->field("agreementName,agreement")->find();
        $configInfo['agreement'] = nl2br($configInfo['agreement']);
        Output::instance()->object($configInfo);
    }

    //商家二维码激活
    public static function vendorCodeActivate($id){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorCode = M("vendor_qrcode");
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $codeInfo = $vendorCode->where("id=$id")->find();
        if($codeInfo['vId']){
            $result['status']=1;
            $result['id']=$codeInfo['vId'];
			$result['name']=$vendorModel->where("id=".$codeInfo['vId'])->getField("name");
        }else{
            $result = $vendorModel->alias("a")
                ->join("inner join wx_store b on a.id=b.vId")
                ->where("a.userId=$userId and a.deleted=0 and b.deleted=0")
                ->field("a.id,b.name,b.id as storeId")
                ->find();
            $data['vId']=$result['id'];
            $data['storeId']=$result['storeId'];
            $data['activateTime']=date("Y-m-d H:i:s");
            $vendorCode->where("id=$id")->save($data);
            $result['status']=0;
        }
        Output::instance()->object($result);
    }
    //商家收支明细
    public function getVendorAccount($id,$start=0,$limit=10){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        Session::switchCustomer($cid);
        $start *= $limit;
        $arr = $accountVendor->where("id=$id")
            ->limit($start,$limit)->order("createTime desc")->select();
        if($arr){
            foreach($arr as $key=>$value){
                $arr[$key]['createTime']=date("Y-m-d H:i",strtotime($value['createTime']));
            }
            $count =$accountVendor->where("id=$id")
               ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //商家门店首页
        public static function getStoreIndex($id,$codeId){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        $storeModel = M("store");
        $couponModel = M("module_coupon");
        $showGroup = M("store_show_group");
        $showModel = M("store_show");
		$vendorCode = M("vendor_qrcode");
        Session::switchCustomer($cid);
		if(!$id){
			$id = $vendorCode->where("id=$codeId")->getField("vId");
		}
        $vendorUserId = $vendorModel->where("id=$id")->getField("userId");
        $storeInfo = $storeModel->where("vId=$id and deleted=0")->field("id,vId,name,phone,address,picUrl1,province,city,country,tel,longitude,latitude")->find();
        if($storeInfo['tel']){
            $storeInfo['tel'] = explode(",",$storeInfo['tel']);
        }
        if($storeInfo['picUrl1']){
            $storeInfo['picUrl1'] = json_decode($storeInfo['picUrl1'],true);
        }
        $storeId= $storeInfo['id'];
        if($userId!=$vendorUserId){
            self::addVisitLog($id,$userId,$storeId,"首页","商家首页","vendorIndex/vendorIndex");
            $result['isSelf']=0;
        }else{
            $result['isSelf']=1;
        }
        $couponList = $couponModel->alias("a")
            ->join("wx_module_user_coupon b on a.id=b.couponId and b.userId=$userId and  status=0")
            ->where("a.vId=$id and a.deleted=0")
            ->field("a.id,a.name,a.money,a.isEffective,a.startTime,a.endTime,a.recommend,a.isVisit,a.visitNum,b.id as partake")
            ->order("a.createTime desc")
            ->select();
        $showList = $showGroup->alias("a")
            ->join("inner join wx_store_show b on a.id=b.groupId")
            ->where("a.storeId=$storeId")
            ->field("a.name,a.id,count(b.id) as count")
            ->group("a.id")
            ->select();
        foreach($showList as $key=>$value){
            $showList[$key]['list']=$showModel->where("groupId=".$value['id'])->field("name,picUrl,id")->limit("0,6")->select();
        }
        $result['storeInfo']=$storeInfo;
        $result['couponList']=$couponList;
        $result['showList']=$showList;
        Output::instance()->object($result);
    }
    //获得轮播图所有图片
    public function getStoreInfo($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M("store");
        Session::switchCustomer($cid);
		$result = $storeModel->where("id=$id")->field("id,vId,name,phone,address,picUrl1,province,city,country,tel,latitude,longitude")->find();
		if($result['picUrl1']){
			 $result['picUrl']=json_decode($result['picUrl1'],true);
		}
		if($result['tel']){
			$result['tel']=explode(",",$result['tel']);
		}
        Output::instance()->object($result);
    }
    //添加浏览记录
    public function addVisitLog($vid,$userId,$storeId,$keywords,$descrition,$url){
        $cid=Session::$user['customerId'];
        Session::switchCustomer($cid);
        $visitLog = M("vendor_visit_log");
        $data['vid']=$vid;
        $data['storeId']=$storeId;
        $data['userId']=$userId;
        $data['keywords']=$keywords;
        $data['descrition']=$descrition;
        $data['url']=$url;
        $data["createTime"] = date("Y-m-d H:i:s");
        $visitLog->add($data);
    }
    //所有展示图片
    public static function getAllShow($id,$start,$limit,$isAll=0){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $showModel = M("store_show");
        $showGroup = M("store_show_group");
        Session::switchCustomer($cid);
        if($isAll){
            $result['name'] = $showGroup->where("id=$id")->getField("name");
            $result['list'] = $showModel->where("groupId=$id")->select();
            Output::instance()->object($result);
        }else{
            $start*=$limit;
            $arr = $showModel->where("groupId=$id")->limit($start,$limit)->select();
            if($arr){
                $count = $showModel->where("groupId=$id")->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }
        }

    }
    //删除分组
    public static function delShowGroup($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $showGroup = M("store_show_group");
        $showModel = M("store_show");
        Session::switchCustomer($cid);
        $showGroup->where("id=$id")->delete();
        $showModel->where("groupId=$id")->delete();
        Output::instance()->resultCode();
    }
    //设置分组
    public static function setShowGroup($name,$list,$id=null){
        $cid=Session::$user['customerId'];
        $userId= Session::$user['userId'];
        Session::switchCustomer(0);
        $showGroup = M("store_show_group");
        $showModel = M("store_show");
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $data['name']=$name;
        if($id){
            $showGroup->where("id=$id")->setField("name",$name);
            $showModel->where("groupId=$id")->delete();
        }else{
            $vendorInfo = $vendorModel->alias("a")
                ->join("inner join wx_store b on a.id=b.vId")
                ->where("a.userId=$userId and a.deleted=0 and b.deleted=0")
                ->field("a.id,b.id as storeId")
                ->find();
            $data['cid']=$cid;
            $data['vid']=$vendorInfo['id'];
            $data['storeId']=$vendorInfo['storeId'];
            $data['createTime']=date("Y-m-d H:i:s");
            $id = $showGroup->add($data);
        }
        $data = null;
        $list = json_decode($list,true);
        foreach($list as $key=>$value){
            $data['cid']=$cid;
            $data['groupId']=$id;
            $data['name']=$value['name'];
            $data['picUrl']=$value['picUrl'];
            $data['createTime']=date("Y-m-d H:i:s");
            $showModel->add($data);
        }
        Output::instance()->resultCode();
    }
    //门店设置
    public static function saveStore($name,$phone,$tel,$province,$city,$country,$address,$longitude,$latitude,$id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M("store");
        Session::switchCustomer($cid);
        $storeId= $id;
        $data['name']=$name;
        $data['phone']=$phone;
        $data['tel']=$tel;
        $data['province']=$province;
        $data['city']=$city;
        $data['country']=$country;
        $data['address']=$address;
        $data['longitude']=$longitude;
        $data['latitude']=$latitude;
        $data['updateTime'] = date("Y-m-d H:i:s");
        $storeModel->where("id=$storeId")->save($data);
        $result['id']=$storeId;
        Output::instance()->object($result);
    }
    //保存轮播图
    public static function saveStorePic($id,$picUrl){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M("store");
        Session::switchCustomer($cid);
		$data['picUrl1']=$picUrl;
		$picUrl = json_decode($picUrl,true);
		$data['picUrl']=$picUrl[0]['picUrl'];
        $storeModel->where("id=$id")->save($data);
        Output::instance()->resultCode();
    }
    //商家访问统计
    public static function vendorVisitStatistics($vid,$start,$limit){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        Session::switchCustomer($cid);
        $start*=$limit;
        $arr = $accountVendor->where("vId=$vid and deleted=0")
            ->limit($start,$limit)->order("createTime desc")->select();
        if($arr){
            foreach($arr as $key=>$value){
				$arr[$key]['money'] = number_format($value['money'],2);
                $update = date("Y-m-d",strtotime($value["createTime"]));
                $datatime=date('Y-m-d');
                $yesterday = date("Y-m-d",time()-24*60*60);
                $arr[$key]["time"] = date("H:i",strtotime($value["createTime"]));
                if($update==$datatime){
                    $arr[$key]["day"] = "今天 ";
                }else if($update==$yesterday){
                    $arr[$key]["day"] = "昨天 ";
                }else{
                    $arr[$key]["day"] = date("m-d",strtotime($value["createTime"]));
                }
            }
            $count = $accountVendor->where("vId=$vid and deleted=0")->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    //商家优惠列表
    public static function getCouponList($id,$start=0,$limit=10){
        $start*=$limit;
        R("Vendor/getVendorCoupon",array($id,NULL,$start,$limit));
    }
    //优惠使用详情
    public static function couponUserList($id,$type=0,$start=0,$limit=10){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
        $start *=$limit;
        $where['a.status'] = array("eq",$type);
        $where["a.couponId"]=array("eq",$id);
        $arr = $userCoupon->alias("a")
            ->join("wx_".$cid."_user_weixin_info b on a.userId=b.userId")
            ->join("inner join wx_module_coupon c on a.couponId=c.id")
            ->where($where)
            ->field("a.id,b.nickname,b.headimgurl,a.serialNumber,a.createTime,a.visitedNum,c.visitNum")
            ->limit($start,$limit)
            ->select();
        if($arr){
            foreach($arr as $key=>$value){
                $arr[$key]['createTime']=date("Y/m/d",strtotime($value['createTime']));
            }
            $count =  $userCoupon->alias("a")
                ->join("wx_".$cid."_user_weixin_info b on a.userId=b.userId")
                ->join("inner join wx_module_coupon c on a.couponId=c.id")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }

    //保存优惠券
    public static function saveCoupon($vid,$name,$recommend,$startTime,$endTime,$copiesNum,$id=null){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        $vendorModel = M("mivendor");
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($cid);
        $couponData['name']=$name;
        $couponData['recommend']=$recommend;
        $couponData['startTime']=$startTime;
        $couponData['endTime']=$endTime;
        $couponData['copiesNum']=$copiesNum;
        $couponData['surplusNum']=$copiesNum;
        $couponData['isEffective']=1;
        $couponData['isVisit']=1;
        $couponData['visitNum']=5;
        $num = $copiesNum;
        $couponModel->startTrans();
        if($id){
            $couponInfo =  $couponModel->where("id=$id")->find();
            if($copiesNum<$couponData['copiesNum']){
                Output::instance()->resultCode(1,"数量不能少于原数量");
                return;
            }
            $num = $copiesNum- $couponData['copiesNum'];
            $couponData['updateTime']=date("Y-m-d H:i:s");
            $couponModel->where("id=$id")->save($couponData);
        }else{
            $data['cId']=$cid;
            $data['name']=$name;
            $data['createTime']=date("Y-m-d H:i:s");
            $data['updateTime']=date("Y-m-d H:i:s");
            $data['vId']=$vid;
            $schemeId = $couponScheme->add($data);
            $couponData['vId']=$vid;
            $couponData['schemeId']=$schemeId;
            $couponData['createTime']=date("Y-m-d H:i:s");
            $couponData['updateTime']=date("Y-m-d H:i:s");
            $couponModel->add($couponData);
        }
        if($num>0){
            $result = self::deductionFee($num,$vid);
            if(!$result){
                $couponModel->rollback();
                return;
            }
        }
        $couponModel->commit();
        Output::instance()->resultCode();
    }
    //优惠数量扣费
    public function deductionFee($num,$vid){
        $cid=Session::$user['customerId'];
        $userId=Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        $accountVendor = M("account_vendor");
        Session::switchCustomer($cid);
        $couponCost = $vendorConfig->where("cid=$cid")->getField("couponCost");
        $couponCost = json_decode($couponCost,true);
        $cost = 0;
        foreach($couponCost as $key=>$value){
            if($value['num']==$num){
                $cost = $value['cost'];
                break;
            }
        }
        if($cost>0){
            $vendorInfo = $vendorModel->where("id=$vid")->find();
            if($vendorInfo['balance']<$cost){
                Output::instance()->resultCode(1,"余额不足");
                return false;
            }
            $data['module']='coupon';
            $data['vId']=$vid;
            $data['description']='发布优惠';
            $data['money']=$cost;
            $data['type']=1;
            $data['createTime']=date("Y-m-d H:i:s");
            $data['deleted']=0;
            $accountVendor->add($data);
            $data = null;
            $data['totalRevenue'] = $vendorInfo['totalRevenue']-$cost;
            $data['balance'] = $vendorInfo['balance']-$cost;
            $vendorModel->where("id=$vid")->save($data);
        }
        return true;
    }
    //获得用户优惠核销码
    public function getUserCouponInfo($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
        $result = $userCoupon->alias("a")
            ->join("inner join wx_module_coupon b on a.couponId=b.id")
            ->where("a.id=$id")
            ->field("a.serialNumber,a.id,b.name,b.vId")
            ->find();
        Output::instance()->object($result);

    }
    public function writeOffCoupon($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
        $status = $userCoupon->where("id=$id")->getField("status");

        if($status){
            Output::instance()->resultCode(1,"该优惠使用过!切勿再次使用!");
            return;
        }
        $userCoupon->where("id=$id")->setField("status",1);
        Output::instance()->resultCode();

    }
    //用户参与优惠
    public function joinCoupon($id,$fromUserId=null){
        $cid=Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $userId=Session::$user['userId'];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        $couponSend = M("module_coupon_send");
        $sendDetail = M("module_coupon_send_detail");
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
		$couponInfo = $couponModel->where("id=$id and deleted=0")->find();
		if(!$couponInfo){
			Output::instance()->resultCode(1,"优惠不存在");
			return;
		}
        $partakeRes = $userCoupon->where("userId=$userId and couponId=$id and status=0")->find();
        if($partakeRes){
            Output::instance()->resultCode(1,"已参与过该优惠");
            return;
        }
        $couponInfo = $couponModel->alias("a")
            ->join("inner join wx_module_coupon_scheme b on a.schemeId=b.id")
            ->field("a.*,b.vId")
            ->where("a.id=$id")->find();
        if($couponInfo['surplusNum']<=0){
            Output::instance()->resultCode(1,"该优惠可参与人数已上限");
            return;
        }
        $data['cId']=$cid;
        $data['openid']=$userName;
        $data['userId']=$userId;
        $data['copiesPrice']=$couponInfo['money'];
        $data['copiesNum']=1;
        $data['surplusPrice']=0;
        $data['surplusNum']=0;
        $data['schemeId']=$couponInfo['schemeId'];
        $data['createTime']=date("Y-m-d H:i:s");
        $data['fromModule']="vendor";
        $data['moduleId']=$couponInfo['vId'];
        $sendId = $couponSend->add($data);
        $data = null;
        $data['sendId']=$sendId;
        $data['couponId']=$id;
        $data['copiesNum']=1;
        $data['surplusNum']=0;
        $data['createTime']=date("Y-m-d H:i:s");
        $data['updateTime']=date("Y-m-d H:i:s");
        $detailId = $sendDetail->add($data);
        $data = null;
        $data['openid']=$userName;
        $data['cId']=$cid;
        $data['schemeId']=$couponInfo['schemeId'];
        $data['couponId']=$id;
        $data['sendDetailId']=$detailId;
        $data['number']=1;
        $data['createTime']=date("Y-m-d H:i:s");
        $data['sendId']=$sendId;
        $data['userId']=$userId;
		 $data['receiveUser']=$fromUserId;
        $id= $userCoupon->add($data);
        $couponModel->where("id=$id")->setDec("surplusNum");
		$result['id']=$id;
		 Output::instance()->object($result);

    }
    //编辑详情
    public static function getCouponDetail($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        $vendorConfig = M("vendor_config");
		$vendorModel = M("mivendor");
        Session::switchCustomer($cid);
		if($id){
			 $couponInfo = $couponModel->alias("a")
            ->join("inner join wx_mivendor b on a.vId=b.id")
            ->where("a.id=$id")
            ->field("a.id,a.name,a.recommend,a.copiesNum,a.isEffective,a.startTime,a.endTime,a.createTime,b.balance")
            ->find();
			$couponInfo['startTime'] = date("Y-m-d",strtotime($couponInfo['startTime']));
			$couponInfo['endTime'] = date("Y-m-d",strtotime($couponInfo['endTime']));
		}else{
			$userId=Session::$user['userId'];
			$couponInfo = $vendorModel->where("userId=$userId and deleted=0")->field("balance")->find();
		}
		$couponInfo['balance'] = number_format($couponInfo['balance'],2);
        $couponCost = $vendorConfig->where("cid=$cid")->getField("couponCost");
        if($couponCost){
            $couponInfo['couponCost'] = json_decode($couponCost,true);
        }
        Output::instance()->object($couponInfo);
    }
    //浏览商家优惠
    public static function visitCoupon($id,$fromUserId){
        $cid=Session::$user['customerId'];
        $userId=Session::$user['userId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        $couponVisit = M("module_user_coupon_visit");
		$vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $weixinInfo = M("user_weixin_info");
		$partakeId = $id;
		$result['isSelf']=1;
		if($fromUserId){
			$partakeId = $userCoupon->alias("a")
			->join("wx_module_user_coupon b on a.couponId=b.couponId")
			->where("a.id=$id and b.userId=$userId and b.status=0")->getField("b.id");
			if(!$partakeId){
				$result['isSelf']=0;
				$partakeId=$id;
			}
		}
        $couponInfo = $userCoupon->alias("a")
            ->join("inner join wx_module_coupon b on a.couponId=b.id")
            ->join("inner join wx_module_coupon_scheme c on b.schemeId=c.id")
            ->join("inner join wx_store d on d.vId=c.vId and d.deleted=0")
            ->where("a.id=$partakeId")
            ->field("a.id,a.userId,a.visitedNum,b.name,b.recommend,b.startTime,b.endTime,b.visitNum,d.name as storeName,d.id as storeId,
            d.longitude,d.latitude,d.province,d.city,d.country,d.address,d.tel,d.vId,a.status,d.id as storeId,a.couponId,a.receiveUser,b.deleted")
            ->find();
			if($couponInfo['tel']){
				$couponInfo['tel'] = explode(",",$couponInfo['tel']);
			}
			//$couponInfo['recommend']=nl2br($couponInfo['recommend']);
		if($fromUserId){
			$where['userId']=array("eq",$fromUserId);
			$userInfo = $weixinInfo->where($where)->field("nickname,headimgurl")->find();
		}else if($couponInfo['receiveUser']){
			$where['userId']=array("eq",$couponInfo['receiveUser']);
			$userInfo = $weixinInfo->where($where)->field("nickname,headimgurl")->find();
		}else{
			$userInfo = $vendorModel->alias("a")
				->join("wx_".$cid."_user_weixin_info b on a.userId=b.userId")
				->field("b.nickname,b.headimgurl")
				->where("a.id=".$couponInfo['vId'])
				->find();
		}
		$userInfo['userId']=$userId;
        $result['userInfo']=$userInfo;
        $couponInfo['startTime'] = date("Y.m.d",strtotime($couponInfo['startTime']));
        $couponInfo['endTime'] = date("Y.m.d",strtotime($couponInfo['endTime']));
		self::addVisitLog($couponInfo['vId'],$userId,$couponInfo['storeId'],"优惠",$couponInfo['name'],"couponInfo/couponInfo");
        if($fromUserId&&$userId!=$fromUserId){
            $visitResult  =$couponVisit->where("userCouponId=$id and userId=$userId")->find();
            if(!$visitResult&&$couponInfo['visitedNum']<$couponInfo['visitNum']){
                $data['cid']=$cid;
                $data['userCouponId']=$id;
                $data['userId']=$userId;
                $data['createTime']=date("Y-m-d H:i:s");
                $visitResult = $couponVisit->add($data);
                if($visitResult){
                    $userCoupon->where("id=$id")->setInc("visitedNum");
                }
            }
        }
        $result['visitList']=$couponVisit->alias("a")
            ->join("wx_".$cid."_user_weixin_info b on a.userId=b.userId")
            ->where("a.userCouponId=$partakeId")
            ->order("a.createTime desc")
            ->field("b.headimgurl")->select();
        $result['couponInfo']=$couponInfo;
        Output::instance()->object($result);
    }
    //用户使用优惠
    public function useCoupon($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
        $couponInfo = $userCoupon->alias("a")
            ->join("inner join wx_module_coupon b on a.couponId = b.id")
            ->where("a.id=$id")
            ->field("a.visitedNum,b.visitNum,b.isVisit,b.startTime,b.endTime,a.serialNumber,b.name")
            ->find();
        $time = time();
        if(!($time>strtotime($couponInfo['startTime'])&&$time<strtotime($couponInfo['endTime']))){
            Output::instance()->resultCode(1,"不在可用时间内");
            return;
        }
        if($couponInfo['isVisit']&&$couponInfo['visitedNum']>=$couponInfo['visitNum']){
            if(!$couponInfo['serialNumber']){
                $serialNumber = self::getCouponSerialNumber();
                $userCoupon->where("id=$id")->setField("serialNumber",$serialNumber);
            }else{
                $serialNumber=$couponInfo['serialNumber'];
            }
            $result['name']=$couponInfo['name'];
            $result['serialNumber']=$serialNumber;
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(1,"不满足使用条件");
        }
    }

    //生成12位随机码
    private function getCouponSerialNumber(){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $userCoupon = M("module_user_coupon");
        Session::switchCustomer($cid);
        $serialNumber='';
        $serialNumber.= rand(1000, 9999);
        $serialNumber.=' '. rand(1000, 9999);
        $serialNumber.=' '.rand(1000, 999);
        $where['serialNumber']=array("eq",$serialNumber);
        $where['deleted']=array("eq",0);
        $result = $userCoupon->where($where)->find();
        if($result){
            self::getCouponSerialNumber();
        }else{
            return $serialNumber;
        }
    }

    //删除优惠
    public function delCoupon($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($cid);
        $schemeId = $couponModel->where("id=$id")->getField("schemeId");
        $couponModel->where("id=$id")->setField("deleted",1);
        $couponScheme->where("id=$schemeId")->setField("deleted",1);
        Output::instance()->resultCode();
    }
    //地区选择
    public function getCity($id,$province,$city){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $cityModel = M("city");
        Session::switchCustomer($cid);
        if($province){
            $where['level']=array("eq",0);
            $result['province'] = $cityModel->where($where)->order("first_letter asc")->field("id,name")->select();
            $id = $cityModel->where("name = '$province' and level=0")->getField("id");
            $result['city'] = $cityModel->where("parent_id=$id")->order("first_letter asc")->field("id,name")->select();
            if($city){
                $id = $cityModel->where("name = '$city' and parent_id=$id")->getField("id");
            }else{
                $id = $result['city'][0]['id'];
            }
            $result['country'] = $cityModel->where("parent_id=$id")->order("first_letter asc")->field("id,name")->select();
        }else{
            !$id?$where['level']=array("eq",0):$where['parent_id']=array("eq",$id);
            $result['list'] = $cityModel->where($where)->order("first_letter asc")->field("id,name")->select();
        }
        Output::instance()->object($result);
    }

}